<%@ Page Language="C#" MasterPageFile="~/Site.master" EnableEventValidation="false" AutoEventWireup="true" Async="true" AsyncTimeOut="100000" %>
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Web" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Diagnostics" %>  
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Business" %>  
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Scripts" %>  
<%@ Register Namespace="SoftwareMonkeys.Scriptech.Web" Assembly="SoftwareMonkeys.Scriptech.Web" TagPrefix="cc" %>
<script runat="server">
	protected string ScriptControlPath = String.Empty;
	protected string ScriptName = String.Empty;
	
	private LogGroup logGroup = null;
	
	private void Page_Init(object sender, EventArgs e)
	{
		logGroup = LogGroup.StartDebug("Initializing the execute script page.");
	}
	
	private void Page_Load(object sender, EventArgs e)
	{
		using (LogGroup logGroup = LogGroup.StartDebug("Loading the execute script page."))
		{
			Response.ContentType = "text/HTML";
			
			try
			{
				using (TimeoutExtender extender = TimeoutExtender.NewMinutes(30))
				{
					Execute();
				}
			}
			catch(Exception ex)
			{
				LogWriter.Error(ex);
				
				throw;
			}
		}
	}
	
	void Execute()
	{
		using (LogGroup logGroup = LogGroup.StartDebug("Executing a script"))
		{
			ScriptName = Request.QueryString["Script"];
			
			LogWriter.Debug("Script name: " + ScriptName);
					
			string shortName = ScriptName;
			
			if (ScriptName.IndexOf("?") > -1)
				shortName = ScriptName.Substring(0, ScriptName.IndexOf("?"));	

			LogWriter.Debug("Short script name: " + shortName);				
					
			if (Path.GetExtension(ScriptName).Trim('.') == "script")
				ScriptControlPath = GetScriptletPath(shortName);
			else
				ScriptControlPath = GetScriptPath(shortName);
				
				ScriptControlPath = ScriptControlPath.Replace("~", Request.ApplicationPath);
				
			LogWriter.Debug("Script control path: " + ScriptControlPath);
				
			Control control = LoadScriptControl(ScriptControlPath);
		
			// If the control is null then don't add it. It means there must have been an error.
			if (control != null)
				ScriptHolder.Controls.Add(control);
		}
	}
	
	protected Control LoadScriptControl(string scriptControlPath)
	{
		Control control = null;
		
		using (LogGroup logGroup = LogGroup.StartDebug("Loading script control."))
		{
			LogWriter.Debug("Script control path: " + scriptControlPath);
		
			try
			{
				control = Page.LoadControl(ScriptControlPath);
			}
			catch (Exception ex)
			{
				if (ex is FileNotFoundException && ex.Message.IndexOf("does not exist") > -1)
					throw new ScriptNotFoundException(Path.GetFileName(scriptControlPath));
				else
				{
					Guid id = new Guid(Request.QueryString["ProcessID"]);
				
					ScriptProcess process = RetrieveStrategy.New<ScriptProcess>().Retrieve<ScriptProcess>("ID", id);
					process.AppendOutput("<p>");
					process.AppendOutput(ex.ToString().Replace(Environment.NewLine, "<br/>"));
					process.AppendOutput("</p>");
					SaveStrategy.New<ScriptProcess>().Save(process);

					LogWriter.Error(ex);

					throw ex;
				}
			}
		}
		
		return control;
	}

	string GetScriptPath (string scriptName)
	{
		string scriptPath = String.Empty;
		
		using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the path for the script '" + scriptName  + "'."))
		{
			
			string scriptsDirectory = "~/Scripts";
			
			scriptPath = scriptsDirectory + "/" + scriptName;
			
			LogWriter.Debug("Script path: " + scriptPath);
		
		}
		
		return scriptPath;
	}

	string GetScriptletPath (string scriptName)
	{
		string newScriptPath = String.Empty;
		
		using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the path to the scriptlet '" + scriptName + "'."))
		{
			string scriptsDirectory = "~/Scripts";
			
			string scriptPath = scriptsDirectory + Path.DirectorySeparatorChar + scriptName;
			
			newScriptPath = ScriptLauncher.GetPreparedScriptletPath(scriptName, scriptPath);
			
			LogWriter.Debug("Scriplet path: " + newScriptPath);
		}
		
		return newScriptPath;
	}

	private string GetEditLink()
	{
		string path = String.Empty;
	
		using (LogGroup logGroup = LogGroup.StartDebug("Creating the edit link."))
		{
			string separator = "?";
			if (Request.Url.ToString().IndexOf("?") > -1)
				separator = "&";
		
			string queryString = Request.Url.Query.ToString();
			if (queryString.ToLower().IndexOf("Script=") > -1)
				queryString = queryString + separator + "Script=" + ScriptName;
		
			path = WebUtilities.MapUrlPath("/EditScript.aspx") + queryString;
			
			LogWriter.Debug("Edit link: " + path);
		}
		
		return path;
	}
	
</script>

<asp:Content ContentPlaceHolderID="MainContent" ID="MainContentContent" runat="server">

<script language="javascript">
var isLoaded = false;

function scrollDown()
{
	if(!isLoaded || !isBottom())
	{ 
		window.scrollTo(0,document.body.scrollHeight);

		setTimeout("scrollDown()", 10);
		
	}
}

function isBottom() {
    return window.pageYOffset >= window.scrollMaxY;
}

function markLoaded()
{
	isLoaded = true;
}

scrollDown();

window.onload = markLoaded;
</script>
<% if (Request.QueryString["ShowTemplate"] != "false"){ %>		
		<div style="text-align: right">
			[<a href='<%= GetEditLink() %>'>Edit Script</a>] - 
			[Create: <a href='<%= WebUtilities.MapUrlPath("/EditScript.aspx?Script=newscript.script") %>'>*.script</a>&nbsp;-&nbsp;<a href='<%= WebUtilities.MapUrlPath("/EditScript.aspx?Script=newscript.ascx") %>'>*.ascx</a>] -
			[<a href='<%= WebUtilities.MapUrlPath("/Scripts.aspx") %>'>Manage Scripts</a>]
		</div>
<% } %>
		<div>Triggering script...</div>
		<span style="visibility:none;">
		<asp:placeholder runat="server" id="ScriptHolder" />
		</span>
</asp:Content>
 


